<?php

namespace NorthernLights\JetBrainsLicensing;

use Klein\Request;
use \SimpleXMLElement;
use NorthernLights\JetBrainsLicensing\Exception\ServerActionException;

/**
 * Class ServerAction
 * @package NorthernLights\JetBrainsLicensing
 */
class ServerAction
{
    /** @var XmlFactory */
    private $xmlFactory;

    /**
     * ServerAction constructor.
     *
     * @param Request $request
     *
     * @throws ServerActionException
     */
    public function __construct(Request $request)
    {
        $actionMethod = $request->action . 'Action';

        if ( ! method_exists($this, $actionMethod)) {
            throw new ServerActionException('Requested action has not been found');
        }

        $this->xmlFactory = new XmlFactory(
            sprintf(
                '%sResponse',
                ucfirst($request->action)
            )
        );

        $this->{$actionMethod}($request);
    }

    /**
     * @return \DOMDocument
     */
    public function getResponseXml(): \DOMDocument
    {
        return $this->xmlFactory->build()->getDomDocument();
    }

    /**
     * @return XmlFactory
     */
    public function getXmlFactory(): XmlFactory
    {
        return $this->xmlFactory;
    }

    /**
     * ping.action
     *
     * @param Request $request
     *
     * @return void
     */
    protected function pingAction(Request $request)
    {
        $xml = $this->xmlFactory;

        $xml->addMultiple([
            'message'      => null,
            'responseCode' => 'OK',
            'salt'         => $request->paramsGet()->get('salt')
        ]);
    }

    /**
     * obtainTicket.action
     *
     * @param Request $request
     *
     * @return void
     */
    protected function obtainTicketAction(Request $request)
    {
        $ticketProperties = new TicketProperties([
            'licensee'    => $request->paramsGet()->get('userName'),
            'licenseType' => 0
        ]);

        $xml = $this->xmlFactory;

        $xml->addMultiple([
            'message'            => null,
            'prolongationPeriod' => 607875500,
            'responseCode'       => 'OK',
            'salt'               => $request->paramsGet()->get('salt'),
            'ticketId'           => 1
        ]);

        $xml->add('ticketProperties', (string)$ticketProperties);
        // Object TicketProperties has __toString ---- ^      ^      ^
    }

    /**
     * releaseTicket.action
     *
     * @param Request $request
     *
     * @return void
     */
    protected function releaseTicketAction(Request $request)
    {
        $xml = $this->xmlFactory;

        $xml->addMultiple([
            'message'      => null,
            'responseCode' => 'OK',
            'salt'         => $request->paramsGet()->get('salt')
        ]);
    }
}
